<template>
  <div class="user-account-page">
    <div class="header">
      <div class="logo">
        <!-- <img src="../assets/tq1.png" alt="" class="tq1" /> -->
      </div>
      <div class="r">
        <div class="r1" @click="home">{{ $t("首页") }}</div>
        <div class="r1" @click="wj">{{ $t("问卷") }}</div>
        <div class="r1" @click="zy">{{ $t("中文/English") }}</div>
        <!-- <div class="r1">{{ $t('关于我们') }}</div> -->
        <!-- <div class="r1">{{ $t('质量保证') }}</div> -->
        <!-- <div class="r1">{{ $t('服务') }}</div> -->
        <div v-if="$store.state.userInfoK.uid != ''" class="r1" @click="goToProfile">
          {{ $store.state.userInfoK.nick_name }}
        </div>
        <div v-else class="r1" @click="login" style="cursor: pointer">
          {{ $t("登录") }}
        </div>
      </div>
    </div>
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧导航面板 -->
      <div class="left-panel">
        <!-- 用户资料卡片 -->
        <div class="profile-card">
          <div class="avatar" @click="uploadAvatar">
            <img v-if="avatarUrl" :src="avatarUrl" alt="头像" class="avatar-image" />
            <div v-else class="avatar-icon">👤</div>
            <div class="upload-overlay">
              <div class="upload-text">{{ $t('点击上传') }}</div>
            </div>
          </div>
          <div class="user-name">{{ user.nick_name }}</div>
          <div class="member-id">{{ $t('成员ID：') }} {{ user.real_name }}</div>
        </div>

        <!-- 导航菜单 -->
        <div class="navigation-menu">
          <div class="menu-section">
            <h3 class="menu-title">{{ $t('关于我') }}</h3>
          </div>
          <div class="menu-section">
            <h3 class="menu-title">{{ $t('用户等级') }}</h3>
            <div class="level-badge">{{ $t('基础') }}</div>
          </div>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="right-panel">
        <!-- 标签页导航 -->
        <div class="tab-navigation">
          <div class="tab-item" :class="{ active: activeTab === 'My Account' }" @click="switchTab('My Account')">
            {{ $t('我的账户') }}
          </div>
          <div class="tab-item" :class="{ active: activeTab === 'Change Password' }"
            @click="switchTab('Change Password')">
            {{ $t('修改密码') }}
          </div>
          <div class="tab-item" :class="{ active: activeTab === 'Cancel Your Account' }"
            @click="switchTab('Cancel Your Account')">
            {{ $t('取消账户') }}
          </div>
        </div>

        <!-- 标签页内容 -->
        <div class="tab-content">
          <!-- My Account 标签页 -->
          <div v-if="activeTab === 'My Account'" class="account-form">
            <!-- 个人信息行 -->
            <div class="form-row">
              <div class="form-field">
                <label class="field-label">{{ $t('用户名') }}</label>
                <input type="text" class="form-input" v-model="userForm.userName" :placeholder="$t('请输入用户名')">
              </div>
              <div class="form-field">
                <label class="field-label">{{ $t('性别') }}</label>
                <el-select v-model="userForm.gender" :placeholder="$t('请选择性别')" size="large" class="form-select">
                  <el-option :label="$t('男')" value="1" />
                  <el-option :label="$t('女')" value="2" />
                </el-select>
              </div>
              <div class="form-field">
                <label class="field-label">{{ $t('出生日期') }}</label>
                <el-date-picker v-model="userForm.birthDate" type="date" :placeholder="$t('请选择出生日期')" size="large"
                  class="form-date-picker" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
              </div>
              <div class="form-field">
                <label class="field-label">{{ $t('邮箱') }}</label>
                <input type="email" class="form-input" v-model="userForm.email" :placeholder="$t('请输入邮箱')">
              </div>
            </div>

            <!-- 地址和联系方式行 -->
            <div class="form-row">
              <div class="form-field">
                <label class="field-label">{{ $t('国家') }}</label>
                <el-select v-model="userForm.country" :placeholder="$t('请选择国家')" @change="onCountryChange" size="large"
                  class="form-select" filterable>
                  <el-option v-for="country in countries" :key="country.code"
                    :label="i18n.locale.value === 'zh' ? country.name : country.name_en" :value="country.code" />
                </el-select>
              </div>
              <div class="form-field">
                <label class="field-label">{{ $t('州') }}</label>
                <el-select v-model="userForm.state" :placeholder="$t('请选择州')" :disabled="!userForm.country" size="large"
                  class="form-select" filterable>
                  <el-option v-for="state in selectedStates" :key="state.code"
                    :label="i18n.locale.value === 'zh' ? state.name : state.name_en" :value="state.code" />
                </el-select>
              </div>
              <div class="form-field">
                <label class="field-label">{{ $t('城市') }}</label>
                <input type="text" class="form-input" v-model="userForm.city" :placeholder="$t('请输入城市')">
              </div>
              <div class="form-field">
                <label class="field-label">{{ $t('邮编') }}</label>
                <input type="text" class="form-input" v-model="userForm.zipCode" :placeholder="$t('请输入邮编')">
              </div>
              <div class="form-field">
                <label class="field-label">{{ $t('电话号码') }}</label>
                <input type="text" class="form-input" v-model="userForm.phoneNumber" :placeholder="$t('请输入电话号码')">
              </div>
            </div>

            <!-- 其他信息行 -->
            <div class="form-row">
              <div class="form-field">
                <label class="field-label">{{ $t('语言') }}</label>
                <div class="language-selector">
                  <!-- 语言选择下拉框 -->
                  <div class="language-dropdown">
                    <el-select v-model="tempLanguageCode" :placeholder="$t('请选择语言')" @change="addLanguage" clearable
                      size="large" class="language-select">
                      <el-option v-for="lang in availableLanguages" :key="lang.codeZ"
                        :label="`${i18n.locale.value === 'zh' ? lang.name_zh : lang.name}`" :value="lang.codeZ">
                        <span class="option-content">
                          <span class="option-text">{{ i18n.locale.value === 'zh' ? lang.name_zh : lang.nameZ }}</span>
                        </span>
                      </el-option>
                    </el-select>
                  </div>
                </div>
              </div>
              <div class="form-field">
                <label class="field-label">{{ $t('语言') }}</label>
                <div class="language-selector">
                  <!-- 已选择的语言标签 -->
                  <div class="selected-languages">
                    <div v-for="lang in selectedLanguages" :key="lang.codeZ" class="language-chip">
                      <span class="chip-text">{{ i18n.locale.value === 'zh' ? lang.name_zh : lang.nameZ }}</span>
                      <span class="chip-remove" @click="removeLanguage(lang.codeZ)">×</span>
                    </div>
                  </div>

                </div>
              </div>
            </div>

            <!-- 保存按钮 -->
            <div class="form-actions">
              <button class="save-button" @click="saveUserInfok">{{ $t('保存') }}</button>
            </div>
          </div>

          <!-- Change Password 标签页 -->
          <div v-if="activeTab === 'Change Password'" class="password-form">
            <el-card class="password-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <el-icon class="header-icon">
                    <Lock />
                  </el-icon>
                  <span class="header-title">{{ $t('修改密码') }}</span>
                </div>
              </template>

              <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="140px"
                class="password-form-content">
                <el-form-item :label="$t('当前密码')" prop="currentPassword">
                  <el-input v-model="passwordForm.currentPassword" type="password" :placeholder="$t('请输入当前密码')"
                    show-password clearable size="large">
                    <template #prefix>
                      <el-icon>
                        <Key />
                      </el-icon>
                    </template>
                  </el-input>
                </el-form-item>

                <el-form-item :label="$t('新密码')" prop="newPassword">
                  <el-input v-model="passwordForm.newPassword" type="password" :placeholder="$t('请输入新密码')" show-password
                    clearable size="large">
                    <template #prefix>
                      <el-icon>
                        <Lock />
                      </el-icon>
                    </template>
                  </el-input>
                </el-form-item>

                <el-form-item :label="$t('确认密码')" prop="confirmPassword">
                  <el-input v-model="passwordForm.confirmPassword" type="password" :placeholder="$t('请再次输入新密码')"
                    show-password clearable size="large">
                    <template #prefix>
                      <el-icon>
                        <Check />
                      </el-icon>
                    </template>
                  </el-input>
                </el-form-item>

                <el-form-item :label="$t('验证码')" prop="verificationCode">
                  <div class="verification-code-container">
                    <el-input v-model="verificationCode" type="text" :placeholder="$t('请输入验证码')" clearable size="large"
                      style="width: 60%">
                      <template #prefix>
                        <el-icon>
                          <Key />
                        </el-icon>
                      </template>
                    </el-input>
                    <el-button type="primary" :disabled="countdown > 0" @click="sendVerificationCode" size="large"
                      style="margin-left: 10px">
                      {{ countdown > 0 ? `${countdown}s` : $t('获取代码') }}
                    </el-button>
                  </div>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" size="large" :loading="passwordLoading" @click="updatePassword"
                    class="update-button">
                    <el-icon>
                      <Upload />
                    </el-icon>
                    {{ $t('更新密码') }}
                  </el-button>
                  <el-button size="large" @click="resetPasswordForm">{{ $t('重置') }}</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>

          <!-- Cancel Your Account 标签页 -->
          <div v-if="activeTab === 'Cancel Your Account'" class="cancel-form">
            <el-card class="cancel-card" shadow="hover">
              <template #header>
                <div class="card-header">
                  <el-icon class="header-icon danger">
                    <Warning />
                  </el-icon>
                  <span class="header-title">{{ $t('取消账户') }}</span>
                </div>
              </template>

              <div class="cancel-content">
                <el-alert :title="$t('重要提醒')" type="warning" :closable="false" show-icon class="warning-alert">
                  <template #default>
                    <p>{{ $t('取消账户后，您将无法恢复您的数据和积分') }}。{{ $t('此操作不可撤销') }}。</p>
                  </template>
                </el-alert>

                <el-divider />

                <div class="warning-list">
                  <h4 class="warning-title">{{ $t('取消账户的后果') }}：</h4>
                  <el-scrollbar height="200px">
                    <ul class="warning-items">
                      <li><el-icon class="warning-item-icon">
                          <CircleClose />
                        </el-icon>{{ $t('您的所有积分将被永久删除') }}</li>
                      <li><el-icon class="warning-item-icon">
                          <CircleClose />
                        </el-icon>{{ $t('您的调查历史将被清除') }}</li>
                      <li><el-icon class="warning-item-icon">
                          <CircleClose />
                        </el-icon>{{ $t('您将无法再访问此账户') }}</li>
                      <li><el-icon class="warning-item-icon">
                          <CircleClose />
                        </el-icon>{{ $t('您的个人资料将被永久删除') }}</li>
                      <li><el-icon class="warning-item-icon">
                          <CircleClose />
                        </el-icon>{{ $t('您将无法接收任何奖励') }}</li>
                      <li><el-icon class="warning-item-icon">
                          <CircleClose />
                        </el-icon>{{ $t('此操作无法撤销') }}</li>
                    </ul>
                  </el-scrollbar>
                </div>

                <el-divider />

                <el-form :model="cancelForm" :rules="cancelRules" ref="cancelFormRef" label-width="120px"
                  class="cancel-form-content">
                  <el-form-item :label="$t('确认密码')" prop="confirmPassword">
                    <el-input v-model="cancelForm.confirmPassword" type="password" :placeholder="$t('请输入密码以确认')"
                      show-password clearable size="large">
                      <template #prefix>
                        <el-icon>
                          <Key />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>

                  <el-form-item prop="agreeTerms">
                    <el-checkbox v-model="cancelForm.agreeTerms" size="large">
                      <span class="checkbox-text">
                        {{ $t('我理解取消账户的后果') }}，{{ $t('并确认要删除我的账户') }}
                      </span>
                    </el-checkbox>
                  </el-form-item>

                  <el-form-item>
                    <el-button type="danger" size="large" :loading="cancelLoading" :disabled="!cancelForm.agreeTerms"
                      @click="confirmCancelAccount" class="cancel-button">
                      <el-icon>
                        <Delete />
                      </el-icon>
                      {{ $t('取消账户') }}
                    </el-button>
                    <el-button size="large" @click="resetCancelForm">{{ $t('重置') }}</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>

    <!-- 隐藏的文件输入框 -->
    <input ref="fileInput" type="file" accept="image/*" style="display: none" @change="handleFileSelect" />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Lock,
  Key,
  Check,
  Upload,
  Warning,
  CircleClose,
  Delete
} from '@element-plus/icons-vue'
import worldData from '../i18n/A_World.js'
import { supportedLanguages, getLanguagesByCountry, getLanguageBycode } from '../data/languages.js'
import { updateloginpw, sendMsg, userInfo2123, saveUserInfo } from '../api/index.js'
import { imgUploads } from '../api/upload.js'

const router = useRouter()
const i18n = useI18n()
const store = useStore()

// 响应式数据
const activeTab = ref('My Account')
const passwordLoading = ref(false)
const cancelLoading = ref(false)
const countdown = ref(0)
const verificationCode = ref('')

// 头像相关数据
const avatarUrl = ref('')
const fileInput = ref(null)
const uploadLoading = ref(false)

// 用户信息
const user = ref({
  uid: "",
  nick_name: "",
  username: "",
})

// 世界数据
const countries = ref(worldData)
const selectedStates = ref([])

// 语言选择相关数据
const selectedLanguages = ref([])
const tempLanguageCode = ref('')
const availableLanguages = computed(() => {
  // 显示所有语言（排除已选择的）
  return supportedLanguages.filter(lang =>
    !selectedLanguages.value.some(selected => selected.codeZ === lang.codeZ)
  )
})

// 用户表单数据
const userForm = reactive({
  userName: '',
  gender: '1', // 1男2女
  birthDate: '',
  email: '',
  country: '',
  state: '',
  city: '',
  zipCode: '',
  phoneNumber: '',
  displayName: ''
})

// 密码表单数据
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 取消账户表单数据
const cancelForm = reactive({
  confirmPassword: '',
  agreeTerms: false
})

// 表单引用
const passwordFormRef = ref()
const cancelFormRef = ref()

// 密码表单验证规则
const passwordRules = {
  currentPassword: [
    { required: true, message: i18n.t('请输入当前密码'), trigger: 'blur' },
    { min: 6, message: i18n.t('密码长度不能少于6位'), trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: i18n.t('请输入新密码'), trigger: 'blur' },
    { min: 6, message: i18n.t('密码长度不能少于6位'), trigger: 'blur' },
    { max: 20, message: i18n.t('密码长度不能超过20位'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: i18n.t('请确认新密码'), trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error(i18n.t('两次输入的密码不一致')))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 取消账户表单验证规则
const cancelRules = {
  confirmPassword: [
    { required: true, message: i18n.t('请输入密码以确认'), trigger: 'blur' }
  ],
  agreeTerms: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error(i18n.t('请确认您理解取消账户的后果')))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 方法
const switchTab = (tabName) => {
  activeTab.value = tabName
}

// 头像上传相关方法
const uploadAvatar = () => {
  fileInput.value.click()
}

const handleFileSelect = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error(i18n.t('请选择图片文件'))
    return
  }

  // 检查文件大小 (限制为5MB)
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error(i18n.t('图片大小不能超过5MB'))
    return
  }

  try {
    uploadLoading.value = true
    // 调用saveUserInfo接口保存头像
    await saveAvatarToServer(file)

  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error(i18n.t('头像上传失败，请重试'))
  } finally {
    uploadLoading.value = false
  }
}

const saveAvatarToServer = async (file) => {
  console.log(file);

  try {
    const formData = new FormData();
    formData.append('avatar', file);
    await sendFormData(formData)
    // 更新用户信息

  } catch (error) {

  }
}
const sendFormData = async (formData) => {
  let timenow = Date.parse(new Date());
  const xhr = new XMLHttpRequest();
  xhr.open('POST', 'https://wjapi.surveydiscovery.com/api/user/saveUserInfo', true);
  xhr.setRequestHeader('authorization', "Bearer " + localStorage.getItem("uid") + "." + localStorage.getItem("token") + '.2');
  xhr.onreadystatechange = function () {
    console.log(xhr);
    if(xhr.response){
      let a = JSON.parse(xhr.response);
      if (a.code === 10000) {
      // 上传成功处理逻辑
      setTimeout(() => {
        userInfo2123().then(res => {
          localStorage.setItem('userInfo', JSON.stringify(res.data));
          store.state.userInfoK = res.data
          // 更新头像URL
          if (res.data.avatar) {
            avatarUrl.value = store.state.imgUrl + res.data.avatar
            ElMessage.success(i18n.t('头像保存成功'))
          }
        });
      }, 1000);
    } else {
      ElMessage.error(i18n.t('头像保存失败，请重试'))
    }
    }
    

    
  };
  xhr.send(formData);
}

// 将文件转换为base64
const fileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

const home = () => {
  router.push("/home");
};

const wj = () => {
  router.push("/homepage");
};

const zy = () => {
  // i18n.locale.value
  if (i18n.locale.value === 'zh') {
    i18n.locale.value = 'en'
    cookie.set('localLang', 'en')
    location.reload()
  } else {
    i18n.locale.value = 'zh'
    cookie.set('localLang', 'zh')
    location.reload()
  }
};

// 国家变化处理
const onCountryChange = () => {
  console.log(userForm.country);
  console.log();
  countries.value.forEach(item => {
    if (item.code === userForm.country) {
      selectedCountryCode.value = item.code
      selectedCountryName_en.value = item.name_en
      selectedStateName.value = item.name
    }
  });
  const selectedCountry = countries.value.find(country => country.code === userForm.country)
  if (selectedCountry) {
    selectedStates.value = selectedCountry.provinces || []


  } else {
    selectedStates.value = []
  }
  // 重置州的选择
  userForm.state = ''
}

// 添加语言
const addLanguage = () => {
  if (tempLanguageCode.value) {
    const language = getLanguageBycode(tempLanguageCode.value)
    if (language && !selectedLanguages.value.some(lang => lang.codeZ === language.codeZ)) {
      selectedLanguages.value.push(language)
    }
    tempLanguageCode.value = ''
  }
}

// 移除语言
const removeLanguage = (languageCode) => {
  selectedLanguages.value = selectedLanguages.value.filter(lang => lang.codeZ !== languageCode)
}
const selectedCountryCode = ref('')
const selectedStateName = ref('')
const selectedCountryName_en = ref('')
// 保存用户信息
const saveUserInfok = async () => {
  try {
    // 获取选中的国家和州信息
    const selectedCountry = countries.value.find(country => country.code === userForm.country)
    const selectedState = selectedStates.value.find(state => state.code === userForm.state)

    // 构建接口参数
    const userData = {
      nick_name: userForm.userName,
      birthday: userForm.birthDate,
      gender: userForm.gender,
      country_code: userForm.country,
      country: selectedCountry ? selectedCountry.name : '',
      country_en: selectedCountry ? selectedCountry.name_en : '',
      state_code: selectedCountryCode.value,
      state: selectedStateName.value,
      state_en: selectedCountryName_en.value,
      city: userForm.city,
      zip_code: userForm.zipCode,
      tel: userForm.phoneNumber,
      email: userForm.email,
      languages: JSON.stringify(selectedLanguages.value)
    }


    // 调用真实API
    const response = await saveUserInfo(userData)

    if (response.code === 10000) {
      ElMessage.success({
        message: i18n.t('更新帐户信息成功!'),
        offset: 100,
        duration: 5000,
      })
      const res = await userInfo2123()
      localStorage.setItem('userInfo', JSON.stringify(res.data));
      store.state.userInfoK = res.data;
    } else {
      ElMessage.error({
        message: response.message || i18n.t('更新帐户信息失败，请重试'),
        offset: 100,
        duration: 5000,
      })
    }
  } catch (error) {
    console.error('保存用户信息失败:', error)
    ElMessage.error({
      message: i18n.t('更新帐户信息失败，请重试'),
      offset: 100,
      duration: 5000,
    })
  }
}

// 发送验证码
const sendVerificationCode = async () => {
  try {
    // 调用发送验证码API
    const response = await sendMsg({
      username: user.value.username,
      type: 3,
    });

    if (response.code === 10000) {
      ElMessage.success({
        message: i18n.t("验证码已发送"),
        offset: 100,
        duration: 5000,
      });

      // 开始倒计时
      countdown.value = 120;
      const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      ElMessage.error({
        message: response.message || i18n.t("验证码发送失败，请重试"),
        offset: 100,
        duration: 5000,
      });
    }
  } catch (error) {
    ElMessage.error({
      message: i18n.t("验证码发送失败，请重试"),
      offset: 100,
      duration: 5000,
    });
  }
};

// 更新密码
const updatePassword = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true

    // 调用真实API
    const response = await updateloginpw({
      username: user.value.username,
      password: passwordForm.newPassword,
      code: verificationCode.value,
    });

    ElMessage.success({
      message: i18n.t("更新密码成功!"),
      offset: 100,
      duration: 5000,
    });
    router.push("/login");
  } catch (error) {
    ElMessage.error({
      message: i18n.t("更新密码失败，请重试"),
      offset: 100,
      duration: 5000,
    });
  } finally {
    passwordLoading.value = false
  }
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  verificationCode.value = ''
  passwordFormRef.value?.clearValidate()
}

// 确认取消账户
const confirmCancelAccount = async () => {
  if (!cancelFormRef.value) return

  try {
    await cancelFormRef.value.validate()

    await ElMessageBox.confirm(
      i18n.t('您确定要取消账户吗') + '？' + i18n.t('此操作不可撤销') + '！',
      i18n.t('确认取消账户'),
      {
        confirmButtonText: i18n.t('确定取消'),
        cancelButtonText: i18n.t('取消'),
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    cancelLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))

    ElMessage.success(i18n.t('账户已成功取消'))
    // 这里可以跳转到登录页面或首页
    router.push('/login')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(i18n.t('取消账户失败') + '，' + i18n.t('请重试'))
    }
  } finally {
    cancelLoading.value = false
  }
}

// 重置取消账户表单
const resetCancelForm = () => {
  cancelForm.confirmPassword = ''
  cancelForm.agreeTerms = false
  cancelFormRef.value?.clearValidate()
}

// 组件挂载时初始化数据
onMounted(async () => {
  // 获取用户信息
  try {
    const res = await userInfo2123()
    localStorage.setItem('userInfo', JSON.stringify(res.data));
    user.value = res.data
    userForm.userName = res.data.nick_name
    userForm.birthDate = res.data.birthday
    userForm.gender = res.data.gender + ''
    userForm.country = res.data.country_code
    userForm.state = res.data.state_code
    selectedCountryCode.value = res.data.country_code
    selectedCountryName_en.value = res.data.country_en
    selectedStateName.value = res.data.country


    userForm.city = res.data.city
    userForm.email = res.data.username
    userForm.zipCode = res.data.zip_code
    userForm.phoneNumber = res.data.tel
    selectedLanguages.value = JSON.parse(res.data.languages)
    store.state.userInfoK = res.data
    // 初始化头像URL
    if (res.data.avatar) {
      avatarUrl.value = store.state.imgUrl + res.data.avatar
    }


  } catch (error) {
    console.error('获取用户信息失败:', error)
  }

  // 初始化美国州数据
  const usCountry = countries.value.find(country => country.code === 'US')
  if (usCountry) {
    selectedStates.value = usCountry.provinces || []
  }

  // // 初始化默认语言（英语）
  // const englishLang = getLanguageBycode('en')
  // if (englishLang) {
  //   selectedLanguages.value = [englishLang]
  // }
})
</script>

<style lang="scss" scoped>
.header {
  padding: 30px 100px;
  margin-bottom: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgb(#409eff, 0.8);
  color: #fff;

  .logo {
    width: 163px;
    height: 67px;

    img {
      width: 100%;
    }
  }

  .r {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .r1 {
      font-family: Arial, Arial;
      font-weight: normal;
      font-size: 25px;
      margin: 0 31px;
      text-align: center;
      font-style: normal;
      text-transform: none;
    }
  }
}

.user-account-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  margin-bottom: 30px;

  .page-title {
    font-size: 28px;
    font-weight: 600;
    color: #333;
    margin: 0 0 10px 0;
  }

  .header-line {
    height: 3px;
    background-color: #409eff;
    width: 100px;
  }
}

.main-content {
  display: flex;
  gap: 30px;
  max-width: 1200px;
  margin: 0 auto;
}

.left-panel {
  width: 300px;
  flex-shrink: 0;
}

.profile-card {
  background-color: #e8f5e8;
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  margin-bottom: 20px;

  .avatar {
    margin-bottom: 15px;
    position: relative;
    cursor: pointer;
    display: inline-block;

    .avatar-icon {
      width: 60px;
      height: 60px;
      background-color: #409eff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      color: white;
      margin: 0 auto;
      transition: all 0.3s ease;
    }

    .avatar-image {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      object-fit: cover;
      margin: 0 auto;
      display: block;
      transition: all 0.3s ease;
    }

    .upload-overlay {
      position: absolute;
      top: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 60px;
      height: 60px;
      background-color: rgba(0, 0, 0, 0.5);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s ease;

      .upload-text {
        color: white;
        font-size: 10px;
        text-align: center;
        font-weight: 500;
      }
    }

    &:hover {
      .upload-overlay {
        opacity: 1;
      }

      .avatar-icon,
      .avatar-image {
        transform: scale(1.05);
      }
    }
  }

  .user-name {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }

  .member-id {
    font-size: 14px;
    color: #666;
  }
}

.navigation-menu {
  background-color: white;
  border-radius: 8px;
  padding: 20px;

  .menu-section {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .menu-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin: 0 0 10px 0;
  }

  .level-badge {
    background-color: #409eff;
    color: white;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    display: inline-block;
  }
}

.right-panel {
  flex: 1;
  background-color: white;
  border-radius: 8px;
  padding: 0;
  margin-bottom: 20px;
}

.tab-navigation {
  display: flex;
  border-bottom: 1px solid #e0e0e0;

  .tab-item {
    padding: 15px 20px;
    cursor: pointer;
    font-size: 16px;
    color: #409eff;
    border-bottom: 3px solid transparent;
    transition: all 0.3s ease;

    &.active {
      background-color: #e8f5e8;
      color: #333;
      border-bottom-color: #409eff;
    }

    &:hover:not(.active) {
      background-color: #f0f0f0;
    }
  }
}

.tab-content {
  padding: 30px;
}

.account-form {
  .form-row {
    display: flex;
    gap: 20px;
    margin-bottom: 25px;
    flex-wrap: wrap;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .form-field {
    flex: 1;
    min-width: 200px;

    .field-label {
      display: block;
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
      font-weight: 500;
    }

    .field-value {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      padding: 8px 0;
    }

    .form-input {
      width: 100%;
      padding: 10px 12px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
      background-color: white;

      &:focus {
        outline: none;
        border-color: #409eff;
      }
    }

    // Element Plus Select 组件样式


    // Element Plus DatePicker 组件样式
    .form-date-picker {
      width: 100%;

      :deep(.el-input__wrapper) {
        border-radius: 8px;
        box-shadow: 0 0 0 1px #dcdfe6 inset;
        transition: all 0.3s ease;

        &:hover {
          box-shadow: 0 0 0 1px #409eff inset;
        }

        &.is-focus {
          box-shadow: 0 0 0 1px #409eff inset;
        }
      }

      :deep(.el-input__inner) {
        font-size: 14px;
        color: #606266;
      }

      :deep(.el-input__placeholder) {
        color: #c0c4cc;
        font-size: 14px;
      }

      :deep(.el-input__suffix) {
        .el-input__suffix-inner {
          .el-icon {
            color: #c0c4cc;
          }
        }
      }
    }

  }

  .language-chip {
    display: inline-flex;
    align-items: center;
    background-color: #409eff;
    color: white;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 14px;
    margin: 4px;

    .chip-flag {
      margin-right: 6px;
      font-size: 16px;
    }

    .chip-text {
      margin-right: 8px;
    }

    .chip-remove {
      cursor: pointer;
      font-weight: bold;
      font-size: 16px;

      &:hover {
        opacity: 0.8;
      }
    }
  }
}

// 语言选择器样式
.language-selector {
  .selected-languages {
    margin-bottom: 10px;
    min-height: 40px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 6px;
    background-color: #fafafa;
  }

  .language-dropdown {
    .language-select {
      width: 100%;

      :deep(.el-input__wrapper) {
        border-radius: 8px;
        box-shadow: 0 0 0 1px #dcdfe6 inset;
        transition: all 0.3s ease;

        &:hover {
          box-shadow: 0 0 0 1px #409eff inset;
        }

        &.is-focus {
          box-shadow: 0 0 0 1px #409eff inset;
        }
      }

      :deep(.el-input__inner) {
        font-size: 14px;
        color: #606266;
      }

      :deep(.el-select__placeholder) {
        color: #c0c4cc;
        font-size: 14px;
      }
    }
  }
}

// Element Plus 选项样式
:deep(.el-select-dropdown__item) {
  padding: 8px 20px;

  .option-content {
    display: flex;
    align-items: center;

    .option-flag {
      margin-right: 8px;
      font-size: 16px;
    }

    .option-text {
      font-size: 14px;
      color: #606266;
    }
  }

  &:hover {
    background-color: #f5f7fa;
  }

  &.is-selected {
    background-color: #409eff;
    color: white;

    .option-content .option-text {
      color: white;
    }
  }
}

.form-actions {
  margin-top: 30px;

  .save-button {
    background-color: #409eff;
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 6px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s ease;

    &:hover {
      background-color: #337ecc;
    }
  }
}

// Element Plus 卡片样式
.password-card,
.cancel-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

  .card-header {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;

    .header-icon {
      margin-right: 10px;
      font-size: 20px;

      &.danger {
        color: #f56c6c;
      }
    }

    .header-title {
      color: #333;
    }
  }
}

// 密码表单样式
.password-form {
  .password-form-content {
    padding: 20px 0;

    .el-form-item {
      margin-bottom: 25px;

      .el-form-item__label {
        font-weight: 500;
        color: #606266;
      }

      .el-input {
        .el-input__wrapper {
          border-radius: 8px;
          box-shadow: 0 0 0 1px #dcdfe6 inset;
          transition: all 0.3s ease;

          &:hover {
            box-shadow: 0 0 0 1px #409eff inset;
          }

          &.is-focus {
            box-shadow: 0 0 0 1px #409eff inset;
          }
        }
      }
    }

    .update-button {
      padding: 12px 30px;
      font-size: 16px;
      border-radius: 8px;

      .el-icon {
        margin-right: 8px;
      }
    }
  }
}

// 取消账户表单样式
.cancel-form {
  .cancel-content {
    padding: 20px 0;

    .warning-alert {
      margin-bottom: 20px;
      border-radius: 8px;

      :deep(.el-alert__content) {
        p {
          margin: 0;
          font-size: 14px;
          line-height: 1.5;
        }
      }
    }

    .warning-list {
      margin: 20px 0;

      .warning-title {
        font-size: 16px;
        font-weight: 600;
        color: #e6a23c;
        margin: 0 0 15px 0;
      }

      .warning-items {
        list-style: none;
        padding: 0;
        margin: 0;

        li {
          display: flex;
          align-items: center;
          padding: 8px 0;
          font-size: 14px;
          color: #606266;

          .warning-item-icon {
            margin-right: 10px;
            color: #f56c6c;
            font-size: 16px;
          }
        }
      }
    }

    .cancel-form-content {
      .el-form-item {
        margin-bottom: 25px;

        .el-form-item__label {
          font-weight: 500;
          color: #606266;
        }

        .el-input {
          .el-input__wrapper {
            border-radius: 8px;
            box-shadow: 0 0 0 1px #dcdfe6 inset;
            transition: all 0.3s ease;

            &:hover {
              box-shadow: 0 0 0 1px #f56c6c inset;
            }

            &.is-focus {
              box-shadow: 0 0 0 1px #f56c6c inset;
            }
          }
        }

        .el-checkbox {
          .el-checkbox__label {
            font-size: 14px;
            color: #606266;
            line-height: 1.5;
          }
        }

        .verification-code-container {
          display: flex;
          align-items: center;
          gap: 10px;

          .el-input {
            flex: 1;
          }

          .el-button {
            flex-shrink: 0;
          }
        }
      }

      .cancel-button {
        padding: 12px 30px;
        font-size: 16px;
        border-radius: 8px;

        .el-icon {
          margin-right: 8px;
        }

        &:disabled {
          opacity: 0.6;
          cursor: not-allowed;
        }
      }
    }
  }
}

// Element Plus 组件全局样式覆盖
:deep(.el-card__header) {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-divider) {
  margin: 20px 0;
}

:deep(.el-scrollbar__view) {
  padding-right: 10px;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;

  &.el-button--primary {
    background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
    border: none;

    &:hover {
      background: linear-gradient(135deg, #337ecc 0%, #2c6aa0 100%);
    }
  }

  &.el-button--danger {
    background: linear-gradient(135deg, #f56c6c 0%, #e74c3c 100%);
    border: none;

    &:hover {
      background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
    }
  }
}

:deep(.el-form-item__error) {
  font-size: 12px;
  color: #f56c6c;
}

// 响应式设计
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }

  .left-panel {
    width: 100%;
  }

  .form-row {
    flex-direction: column;

    .form-field {
      min-width: 100%;
    }
  }

  .tab-navigation {
    flex-direction: column;

    .tab-item {
      text-align: center;
    }
  }
}
</style>